package chaincode

import (
	"encoding/json"

	"github.com/hyperledger/fabric-chaincode-go/shim"
	"github.com/hyperledger/fabric-protos-go/peer"
)

type SmartContract struct{}

func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {
	return shim.Success(nil)
}

// Invoke
func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	//获取需调用的方法名，及调用的参数
	function, args := stub.GetFunctionAndParameters()
	switch function {
	case "CreateAsset":
		return s.CreateAsset(stub, args)
	case "QueryAsset":
		return s.QueryAsset(stub, args)
	case "TransferAsset":
		return s.TransferAsset(stub, args)
	default:
		return shim.Error("...")
	}
}

// 资产结构
type Asset struct {
	ID    string `json:id`
	Owner string `json:owner`
}

// 创建资产
func (s *SmartContract) CreateAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	//创建资产对象
	asset := Asset{ID: args[0], Owner: args[1]}

	//json
	assetJSON, _ := json.Marshal(asset)

	//存储到链上
	stub.PutState(args[0], assetJSON)

	return shim.Success(nil)
}

// 查询资产
func (s *SmartContract) QueryAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	//根据资产id查询资产
	assetJSON, _ := stub.GetState(args[0])
	return shim.Success(assetJSON)
}

// 转移资产
func (s *SmartContract) TransferAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	//从账本中获取资产
	assetJSON, _ := stub.GetState(args[0])
	//反序列化
	var asset Asset
	json.Unmarshal(assetJSON, &asset)

	//修改资产所有者
	asset.Owner = args[1]
	updateJSON, _ := json.Marshal(asset)
	stub.PutState(args[0], updateJSON)
	return shim.Success(updateJSON)

}
